const express = require("express");
const router = express.Router();
const { executeQuery } = require("../../mysql");
const { getMajorNameById } = require("../../public");

router.post("/update-teacher", async (req, res) => {
    try {
        const { id, name, tel, sex, subject, password, is_class_teacher, grade, activeClass, major } = req.body;

        // Convert is_class_teacher to number explicitly
        const isClassTeacherNumber = Number(is_class_teacher);

        let  values ;

        // Prepare SQL query
        let sql = `
            UPDATE tb_teacher 
            SET 
                name = ?,
                tel = ?,
                sex = ?,
                subject = ?,
                password = ?,
                is_class_teacher = ?`;

        if (isClassTeacherNumber === 1) {
            let majorName = null;
            let majorId = null;
            
            try {
                // Fetch major name using major id
                majorName = await getMajorNameById(major);
                majorId = major; // Assuming majorId is the same as major for simplicity
            } catch (error) {
                console.error('Error fetching major name:', error.message);
                throw new Error('Failed to fetch major name');
            }

            // Add class-related fields to SQL query
            sql += `,
                grade = ?,
                class_name = ?,
                major = ?,
                major_id = ?`;

            values = [name, tel, sex, subject, password, isClassTeacherNumber, grade, activeClass, majorName, majorId, id];
        } else {
            // When is_class_teacher is 0, reset class-related fields to NULL
            sql += `,
                grade = NULL,
                class_name = NULL,
                major = NULL,
                major_id = NULL`;

            values = [name, tel, sex, subject, password, isClassTeacherNumber, id];
        }

        // Complete the SQL query with WHERE clause
        sql += `
            WHERE 
                id = ?`;

        // Debug output
        console.log('SQL:', sql);
        console.log('Values:', values);

        // Execute the SQL query
        const result = await executeQuery(sql, values);

        console.log('Teacher updated successfully', result);

        res.json({ success: true }); // Send success response to client
    } catch (error) {
        console.error('Error updating teacher:', error.message);
        res.status(500).json({ error: 'Failed to update teacher' }); // Send error response to client
    }
});

module.exports = router;
